<?php

namespace App\Kuafu\Customer\Service;

use App\Kuafu\Base\Service\BaseService;
use App\Kuafu\Common\Service\CommonService;
use App\Kuafu\CouponPackage\Enum\CouponPackageEnum;
use App\Kuafu\CouponPackage\Model\CouponPackageModel;
use App\Kuafu\CouponPackage\Model\CouponPackageOrderModel;
use App\Kuafu\Customer\Enum\CustomerCodeEnum;
use App\Kuafu\Customer\Exceptions\CustomerException;
use App\Kuafu\Customer\Model\CustomerPlatformModel;
use App\Kuafu\Shop\Service\ShopService;
use App\Support\AppletEncrypt;
use Illuminate\Http\Request;

class CustomerPlatformService extends BaseService
{


    public static function addCustomerPlatMapping(array $data)
    {
        $s = CustomerPlatformModel::addData($data);
        if (!$s) {
            throw new CustomerException(CustomerCodeEnum::ERR_CUSTOMER_DB_ADD);
        }
        return $s;
    }

    public static function setCustomerMapping($unionid, $platformId, $value)
    {
        return CustomerPlatformModel::setData($unionid, $platformId, $value);
    }

    public static function getUserInfoByUnionid($unionid, $platformId, $field)
    {
        return CustomerPlatformModel::getUserInfoByColumn(['unionid' => $unionid, 'platformId' => $platformId], $field);
    }

    public static function getUserIdByUnionId(string $unionid, int $platformId)
    {
        $userInfo = CustomerPlatformModel::getUserInfoByColumn(['unionid' => $unionid, 'platformId' => $platformId],
            'userId');

        return $userInfo->userId ?? 0;
    }

    public static function setUserIdByUnionid($unionid, $platId, $userId)
    {
        return CustomerPlatformModel::query()
                                    ->where(['unionid' => $unionid, 'platformId' => $platId])
                                    ->update(['userId' => $userId]);
    }

    public static function setOpenIdByUnionId($unionid, $platformId, $openId)
    {
        return CustomerPlatformModel::query()
                                    ->where(['unionid' => $unionid, 'platformId' => $platformId])
                                    ->update(['openId' => $openId]);
    }

    public static function getUserId(Request $request)
    {
        $appletToken = $request->header('APPLET-TOKEN');
        if ($appletToken == "test" && config('app.env') == 'dev') {
            return 1;
        }
        $userUnionid = AppletEncrypt::getInstance()->getUserUnionid($appletToken);
        return CustomerPlatformModel::query()
                                    ->where(['unionid' => $userUnionid, 'platformId' => $request->header('platformId')])
                                    ->value('userId');
    }

    /**
     * @param $userId int 用户id
     * @param $platformId int 平台id
     * @param $field array 查询结果 ['id','openid']
     * @return \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Model|object|null
     */
    public static function getUserFieldByUserId($userId, $platformId, $field)
    {
        return CustomerPlatformModel::getUserInfoByColumn(['userId' => $userId, 'platformId' => $platformId], $field);
    }

    /**
     * 小程序获取用户的OpenId
     * @param Request $request
     * @return \Illuminate\Database\Eloquent\HigherOrderBuilderProxy|mixed|string
     * @throws CustomerException
     */
    public static function getOpenId(Request $request)
    {
        $userId = CustomerPlatformService::getUserId($request);
        if (!$userId) {
            throw new CustomerException(CustomerCodeEnum::ERR_CUSTOMER_GET_USER_ID);
        }

        $platformId = $request->header('platformId');

        $userOpenId = CustomerPlatformService::getUserFieldByUserId($userId, $platformId, ['openid'])->openid ?? '';
        if (!$userOpenId) {
            throw new CustomerException(CustomerCodeEnum::ERR_CUSTOMER_GET_OPEN_ID);
        }

        return [$userId, $userOpenId];
    }

    //获取券包信息
    public static function couponPackageInfo($shopId, $userId, $couponPackageId, $isPop = false)
    {
        //通过门店ID获得门店的类型
        $shop = ShopService::getShopInfo($shopId);
        if (!$shop) {
            return [];
        }
        //店铺的类型
        $shopType = $shop->type;
        //获取星期
        $day           = date("w") != 0 ? date("w") : 7;
        $couponPackage = CouponPackageModel::query()
                                           ->where('status', CouponPackageEnum::STATUS_ON)
                                           ->where('startAt', '<=', time())
                                           ->where('endAt', '>=', time())
                                           ->when($couponPackageId > 0, function ($query) use ($couponPackageId) {
                                               $query->where('id', $couponPackageId);
                                           })
                                           ->where(function ($query) use ($shopType, $shopId) {
                                               $query->whereIn('shopType',
                                                   [CouponPackageEnum::SHOP_TYPE_ALL, $shopType])
                                                     ->orWhereHas('couponPackageShopMappingRel',
                                                         function ($query) use ($shopId) {
                                                             $query->where('shopId', $shopId);
                                                         });
                                           })
                                           ->when($isPop, function ($query) use ($day) {
                                               $query->where('popDate', 'like', "%$day%");
                                           })
                                           ->orderBy('id', 'desc')
                                           ->first();

        if (empty($couponPackage)) {
            return [];
        }
        //判断用户是否已经购买
        $buyInfo       = CouponPackageOrderModel::checkBuyOrder($userId, $couponPackage->id);
        $couponPackage = self::popupWindows($couponPackage);
        return [
            'isBuy'        => $buyInfo ? true : false,
            'isPopup'      => $couponPackage['isPopup'],
            'couponDetail' => $couponPackage['couponPackageDetail']
        ];
    }

    //判断是否弹窗以及返回详情
    public static function popupWindows($couponPackageId)
    {
        if ($couponPackageId instanceof CouponPackageModel) {
            $couponPackageModel = $couponPackageId;
        } else {
            $couponPackageModel = CouponPackageModel::query()->find($couponPackageId)->toArray();
        }
        $couponPackageModel['couponPackageImg'] = CommonService::joinImageUrl($couponPackageModel['couponPackageImg']) ?? '';
        $couponPackageModel['miniAdvPopImg']    = CommonService::joinImageUrl($couponPackageModel['miniAdvPopImg']) ?? '';
        $couponPackageModel['bannerImg']        = CommonService::joinImageUrl($couponPackageModel['bannerImg']) ?? '';
        $couponPackageModel['detailImg']        = CommonService::joinImageUrl($couponPackageModel['detailImg']) ?? '';
        $time                                   = date('His');
        if ($couponPackageModel['startAt'] < time() && $couponPackageModel['endAt'] > time() && $couponPackageModel['miniAdvPopSwitch'] == CouponPackageEnum::MINI_ADV_POP_SWITCH_ON) {
            if ($couponPackageModel['dayStartAt'] < $time && $couponPackageModel['dayEndAt'] > $time) {
                return [
                    'isPopup'             => true,
                    'couponPackageDetail' => $couponPackageModel
                ];
            }
        }
        return [
            'isPopup'             => false,
            'couponPackageDetail' => $couponPackageModel
        ];
    }

    /**
     * 通过unionId获取用户信息
     * @param int $platformId
     * @param array $unionIds
     * @return array
     */
    public static function getCustomerPlatformUsers(int$platformId,array $unionIds): array
    {
        return CustomerPlatformModel::query()
                                    ->where('platformId', $platformId)
                                    ->whereIn('unionid', $unionIds)
                                    ->get()
                                    ->toArray();
    }
}
